package com.jiyun.jiyumall.jiyunthird.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.jiyun.jiyunmall.common.utils.Result;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 前端直传到OSS的controller服务
 */
@RestController
public class OssPolicyController {
    @Autowired
    private OSS client;
    @Value("${alibaba.cloud.oss.bucket}")
    private String bucket;
    @Value("${alibaba.cloud.oss.host}")
    private String host;
    @Value("${alibaba.cloud.access-key}")
    private String accessId;

    /*
        客户端请求咱们服务，获取一个签名，这个签名非常重要的
        客户端将来要拿着这数据，以及上传得文件一起给OSS
     */
    @GetMapping("/oss/policy")
    public Result getPolicy() {
        // 拼接一节上传的路径前缀，将来就是oss中的一个目录，我希望一天一个目录如：2022-08-03
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(new Date());
        String dir = dateString + "/";
        try {
            // 设计过期时间
            long expireTime = 30;
            // 求出来未来30秒后的日期时间戳
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            // 设定过期的时间Date对象
            Date expiration = new Date(expireEndTime);
            // 创建个签名的对象
            PolicyConditions policyConds = new PolicyConditions();
            // 设置文件的最大大小，
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 10485760);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            // 拼接最终返回给前端的结果集，前端根据这个结果集，来拼接参数，为下一次请求做准备
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

            return new Result().ok(respMap);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new Result().error();
        }

    }
}
